<?php

/**
 * 默认控制器
 */
class Controller_Hostmanage extends Controller_Abstract
{
    /* ******************************************************************** */
	function actionImport()
    {
        //dump($_SESSION);
		$data = new Helper_ExcelReader();
		$data->setOutputEncoding('utf-8');
		$data->read('1.xls');
		error_reporting(E_ALL ^ E_NOTICE);

		$op=1;$warnc=0;$allinput=array();
		for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
		$lineout=false;
			if($i>2 && $data->sheets[0]['cells'][$i][1]!=''){
				for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
					if($j==1)$ainput=array();
					if($j==1)$ainput['macaddress']=$data->sheets[0]['cells'][$i][1];
					if($j==2)$ainput['ostype']=$data->sheets[0]['cells'][$i][2];
					if($j==3)$ainput['ipaddr']=$data->sheets[0]['cells'][$i][3];
					if($j==4)$ainput['hostname']=$data->sheets[0]['cells'][$i][4];
					if($j==5)$ainput['datetime']=$data->sheets[0]['cells'][$i][5];
					if($j==6)$ainput['descript']=$data->sheets[0]['cells'][$i][6];
					//array_push($ainput,$data->sheets[0]['cells'][$i][$j]);
					//echo $data->sheets[0]['cells'][$i][$j].'|';
				}
				$ainput['connectstate']='0';
				array_push($allinput,$ainput);
			}
		}
		if(count($allinput)>0){
		$allhaves=0;
		foreach ($allinput as $key=>$value){
			try
            {
                $newgroup= new Host($value);
				$newgroup->save();
				$allhaves++;
            }
            catch (QValidator_ValidateFailedException $ex)
            {
                
            }
			
			//print_r($value);
		}
		//$newgroup= new Host($allinput[0]);
		//$newgroup->save();
		echo '成功导入：'.$allhaves;
		}else{
		echo '数据空';
		}
	}

	function actionQuick()
    {
	
	}

	function actionUnhost(){
		$show_box['title'] = '解除主机绑定';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');
			//注意设定用户删除的锁定
			if($this->_context->id)
			{
				$group_id = $this->_context->id;
				list($hid, $gid) = explode('|', $group_id);
				//dump($hid.$gid);
				GrouptoHost::meta()->destroyWhere('hostid = ? and groupid = ?',$hid,$gid);
				if(mysql_affected_rows())
				{
					return $this->_redirectMessage(
					'主机组解除成功', 
					'指定主机组解除成功',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
				}
				else
				{
					return $this->_redirectMessage(
					'主机组解除失败', 
					'指定主机组解除失败',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
				}
			}
			else
			{
				return $this->_redirectMessage(
					'错误操作', 
					'操作错误，返回首页',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
			}
		}
	}

	function actionAdminso(){
		$demo = array();
		// 设置页面列表数目
		$pagesize = 10;
		// 获取当前页数，通常为get方式参数
		//$_REQUEST['start']
		$page = ($_REQUEST['start']/$_REQUEST['limit'])+1;
		$this->_view['pageno']=$page;
		$adming='';
		$select = Hostgroup::find($adming)->limitPage($page,$_REQUEST['limit']);
		$allc=$select->getPagination();
		$totaldata = $allc['record_count'];
		$demostr=$select->order("id desc")->getAll()->toArray();
		$date = date("Y-m-d");
		for($i=0; $i<count($demostr); $i++){
			$demo[] = array("date"=>$demostr[$i]['id'],"pageview"=>$demostr[$i]['groupname'],"ip"=>$demostr[$i]['description'],"visits"=>$demostr[$i]['groupname'],"uv"=>$demostr[$i]['groupname'],"pvuv"=>$demostr[$i]['datetime'],"op"=>$demostr[$i]['description']);
			$date = date("Y-m-d",strtotime($date)-24*3600);
			
		}
		

		//$demo_out = array_slice($demo,$_REQUEST['start'],$_REQUEST['limit']);
		$str = '({"total":"'.$totaldata.'","root":'.json_encode($demo).'})';
		//dump($demostr);
		echo $str;
	}

	function actionAdmins(){
		
		$show_box['title'] = '主机管理首页';
		
		if ($this->_app->currentUserRoles())
        {
			 //区分用户
			 $os = array("admin");

		     $aroles = array();
		     $aroles =split('[,]', $_SESSION['acl_task_userdata']['roles']);
			//dump($aroles);
			$isrightp=false;
			 foreach ($aroles as $value){
				if (in_array(strtolower($value), $os)) {
					$isrightp=true;
					//echo 'opip';
					break;
					//echo "Got Irix";
				}
			 }
			 //echo $isrightp;
			 //echo $_SESSION['acl_task_userdata']['user_id'];
			 $adming='';
			 if(!$isrightp){
				$havegroups = array();
				$select1 = Groupuser::find('userid = ?',$_SESSION['acl_task_userdata']['user_id'])->getAll();
				foreach ($select1 as $av){
					array_push($havegroups,$av->groupid);
					//echo $av->groupid;
				}
				$addconds='';
				//dump($havegroups);
				$hgs=count($havegroups);
				$this->_view['adming']=$hgs;
				if($hgs>0){
					$adming=' id in ('.join(",",$havegroups).') ';
				}else{
					$adming=' id in (-1) ';
				}
			 }else{
				
				$this->_view['adming']=-1;
			 }
			 //END
			
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1','查看'.$show_box['title'],'');

			$table =QDB::getConn();
			$sql = "SELECT DISTINCT groupid FROM `grouptohost`";
			$handel =$table->execute($sql);
			$temp = $handel->fetchAll();
			$allhave = array();
			foreach ($temp as $s){
				$allgroup = array();
				$allgroup['groupid']=$s['groupid'];
				$allhave[$s['groupid']]=$allgroup;
				//echo $s['groupid'];
			}

			//$table =QDB::getConn();
			$sql = "SELECT count( 1 ) AS grouphosts, groupid FROM `grouptohost` GROUP BY `grouptohost`.groupid";
			$handel =$table->execute($sql);
			$temp1 = $handel->fetchAll();
			//$allhosts = array();
			foreach ($temp1 as $s){
				//$allgroup = array();
				//$allgroup['groupid']=$s['groupid'];
				$allhave[$s['groupid']]['hosts']=$s['grouphosts'];
				//echo $s['groupid'];
			}

			//SELECT systeminfo.`macaddress` , hosttable.`id` , systeminfo.`lasttime`
	//		FROM systeminfo
	//		LEFT JOIN hosttable ON hosttable.`macaddress` = systeminfo.`macaddress`
	//		WHERE systeminfo.`lasttime` >= DATE_sub( NOW( ) , INTERVAL 10
	//		MINUTE )
	//		AND systeminfo.`lasttime` < DATE_ADD( NOW( ) , INTERVAL 10
	//		MINUTE )
			//查询据现在20分钟内的主机测试INTERVAL 30 SECOND改为INTERVAL 30 SECOND
			$sql = "SELECT systeminfo.`macaddress`,hosttable.`id`,systeminfo.`lasttime` FROM systeminfo left join hosttable on hosttable.`macaddress` =systeminfo.`macaddress` WHERE systeminfo.`lasttime` >= DATE_sub( NOW( ) , INTERVAL 30 SECOND ) and systeminfo.`lasttime` < DATE_ADD( NOW( ) , INTERVAL 30 SECOND)";
			$handel =$table->execute($sql);
			$temp2 = $handel->fetchAll();
			$achosts = array();
			foreach ($temp2 as $s){
				if(isset($s['id']))
					array_push($achosts,$s['id']);
			}

			if(count($achosts)>0){
				//统计每个组的激活数
				$sql = "SELECT count(1) as grouplives, groupid FROM `grouptohost` WHERE `hostid` IN (".join(",",$achosts).") GROUP BY groupid";
				$handel =$table->execute($sql);
				$temp3 = $handel->fetchAll();
				foreach ($temp3 as $s){
					$allhave[$s['groupid']]['lives']=$s['grouplives'];
				}
			}

			//统计组规则
			$sql = "SELECT count(id) AS configall, groupid FROM `config` GROUP BY groupid";
			$handel =$table->execute($sql);
			$temp2 = $handel->fetchAll();
			$grules = array();
			foreach ($temp2 as $s){
				if(isset($s['configall']))
					$grules[$s['groupid']]=$s['configall'];
				//array_push($achosts,$s['configall']);
			}
			$this->_view['group_config']= $grules;

			//缓存所有主机的管理员
			//SELECT groupid,user_name,userid FROM `grouptouser` left join `sys_acl_users` on `grouptouser`.userid=`sys_acl_users`.user_id
			$sql = "SELECT groupid,user_name,userid FROM `grouptouser` left join `sys_acl_users` on `grouptouser`.userid=`sys_acl_users`.user_id";
			$handel =$table->execute($sql);
			$temp5 = $handel->fetchAll();
			$acadmins = array();
			foreach ($temp5 as $s){
				if(!isset($acadmins[$s['groupid']]))
					$acadmins[$s['groupid']]= array();
				
				array_push($acadmins[$s['groupid']],$s['user_name']);
				//echo $s['user_name'];
			}
			
			foreach ($acadmins as $foo => $tmp2) {
				$allhave[$foo]['adminus']=join(",", $tmp2);
			}
			//print_r($acadmins);
			//print_r($allhave);
			$this->_view['groupc']= $allhave;
			// 设置页面列表数目
			$pagesize = 10;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;
			$select = Hostgroup::find($adming)->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
			if($this->_view['pager']['record_count']>0 && $page=='')
					$page=1;

			
			//echo $this->_view['pager']['record_count'];
			$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'hostmanage|admins|','\')',5);

			$this->_view['pagestr']= $pagediv->show();

		}
	}

	function actionAdmin()
    {
        $show_box['title'] = '设置主机组管理员';
		
		$select = Admin_Permissions::find('controller = ? and action =?', 'hostmanage','index');
		//$this->_view['pager'] = $select->getPagination();
		//$this->_view['group'] = $select->getAll();
		

		foreach($select->getAll() as $uir){
			$pid= $uir->permission_id;
		}

		$select = Admin_RolesHavePermissions::find('permission_id = ?', $pid);
		//$this->_view['group'] = $select->getAll();
		$arr = array();
		
		foreach($select->getAll() as $uir){
			array_push ( $arr, $uir->role_id);
		}
		$rolestr = join(",", $arr);
		$select = Admin_UsersHaveRoles::find('role_id in ('.$rolestr.')');
		$this->_view['group'] = $select->getAll();
		$arr1 = array();
		
		foreach($select->getAll() as $uir){
			array_push ( $arr1, $uir->user_id);
		}
		$userstr = join(",", $arr1);
		$select = Admin_Users::find('user_id in ('.$userstr.')');
		$this->_view['group'] = $select->getAll();
		
		//find('title like ?', '%search_txt%')->getAll();
		
        //dump($_SESSION);
		$this->_view['form'] = new Form_AdminToGroup(url('default::hostlist/adminblind'));
		//echo $_SESSION['acl_task_userdata']['account'];
    }

	function actionViews(){
		$show_box['title'] = '组管理员列表';
		// 设置页面列表数目
		$pagesize = 10;
		// 获取当前页数，通常为get方式参数
		$page = $this->_context->page;
		$group_id = $this->_context->id;
		list($gid, $gname) = explode('|', $group_id);
		//echo $page;
		//echo $this->_context->id;
		$this->_view['gstr']=$gname;
		$this->_view['gnum']=$gid;
		$andstr='';$addkeys='';$andstr1='';
		$this->_view['pageno']=$page;
		
		
		$select = Groupuser::find('groupid = ?',$gid)->limitPage($page, $pagesize);
		$this->_view['pager'] = $select->getPagination();
		$this->_view['group'] = $select->order("id desc")->getAll();
		$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
		if($this->_view['pager']['record_count']>0 && $page=='')
					$page=1;

		//echo $this->_view['pager']['record_count'];
		$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'hostmanage|hostlist|','\')',5);
		$this->_view['pagestr']= $pagediv->show();
	}

	function actionUpload()
    {
        $uploaddir = 'upload/';
		$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

		if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
		  
			//导入数据库
			$data = new Helper_ExcelReader();
			$data->setOutputEncoding('utf-8');
			$data->read($uploadfile);
			error_reporting(E_ALL ^ E_NOTICE);

			$op=1;$warnc=0;$allinput=array();
			for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
			$lineout=false;
				if($i>2 && $data->sheets[0]['cells'][$i][1]!=''){
					for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
						if($j==1)$ainput=array();
						if($j==1)$ainput['macaddress']=$data->sheets[0]['cells'][$i][1];
						if($j==2)$ainput['ostype']=$data->sheets[0]['cells'][$i][2];
						if($j==3)$ainput['ipaddr']=$data->sheets[0]['cells'][$i][3];
						if($j==4)$ainput['hostname']=$data->sheets[0]['cells'][$i][4];
						if($j==5)$ainput['datetime']=$data->sheets[0]['cells'][$i][5];
						if($j==6)$ainput['descript']=$data->sheets[0]['cells'][$i][6];
						//array_push($ainput,$data->sheets[0]['cells'][$i][$j]);
						//echo $data->sheets[0]['cells'][$i][$j].'|';
					}
					$ainput['connectstate']='0';
					array_push($allinput,$ainput);
				}
			}
			if(count($allinput)>0){
			$allhaves=0;
			foreach ($allinput as $key=>$value){
				try
				{
					$newgroup= new Host($value);
					$newgroup->save();
					$allhaves++;
				}
				catch (QValidator_ValidateFailedException $ex)
				{
					
				}
				
				//print_r($value);
			}
			//$newgroup= new Host($allinput[0]);
			//$newgroup->save();
			echo '成功导入：'.$allhaves;
			}else{
			echo '数据空';
			}

		} else {
		  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
		  // Otherwise onSubmit event will not be fired
		  echo "error";
		}
		

		
		//$show_box['title'] = '测试操作1111111111111111';
        //dump($_SESSION);
		//echo '2010';
		//echo $_SESSION['acl_task_userdata']['account'];
    }

	/*Host Manage*/
	function actionHostlist()
    {
		$show_box['title'] = '主机列表';
		// 设置页面列表数目
		$pagesize = 10;
		// 获取当前页数，通常为get方式参数
		$page = $this->_context->page;
		//echo $page;
		//echo $this->_context->id;
		$this->_view['gid']=$this->_context->id;
		$andstr='';$addkeys='';$andstr1='';
		$this->_view['pageno']=$page;
		if ($this->_context->isPOST())
		{
			if($_POST['groupid']!=''){
				$this->_view['gid']=$_POST['groupid'];
			}
		
			if($_POST['searchtxt']!='')
				$addkeys=' hostname like \'%'.$_POST['searchtxt'].'%\'';

			if($_POST['searchip']!=''){
				if($addkeys!='')$andstr=' and ';
				$addkeys.=$andstr.' ipaddr like \'%'.$_POST['searchip'].'%\'';
			}
		}
		if($addkeys!='')$andstr1=' and ';
		$select = Host::find($addkeys.$andstr1.'[group.groupid]= ?',$this->_view['gid'])->limitPage($page, $pagesize);
		$this->_view['pager'] = $select->getPagination();
		$this->_view['group'] = $select->order("id desc")->getAll();
		$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
		if($this->_view['pager']['record_count']>0 && $page=='')
					$page=1;


		//查询激活状态
		$achosts=array();
		$table =QDB::getConn();
		$sql = "SELECT systeminfo.`macaddress`,hosttable.`id`,systeminfo.`lasttime` FROM systeminfo left join hosttable on hosttable.`macaddress` =systeminfo.`macaddress` WHERE systeminfo.`lasttime` >= DATE_sub( NOW( ) , INTERVAL 30 SECOND ) and systeminfo.`lasttime` < DATE_ADD( NOW( ) , INTERVAL 30 SECOND)";
			$handel =$table->execute($sql);
			$temp2 = $handel->fetchAll();
			$achosts = array();
			foreach ($temp2 as $s){
				if(isset($s['macaddress']))
					$achosts[$s['macaddress']]='1';
			}
		$this->_view['alive']=$achosts;
		//print_r($achosts);
		//echo $this->_view['pager']['record_count'];
		$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'hostmanage|hostlist|','\')',5);
		$this->_view['pagestr']= $pagediv->show();
    }

	/*Host Manage*/
	function actionSearch()
    {
		$show_box['title'] = '主机搜索';
		// 设置页面列表数目
		$this->_view['form'] = new Form_HostSearch(url('default::hostmanage/hostlist'));
		$this->_view['form']->import(array('groupid'=>$this->_context->id));
		$this->_view['form']->element('groupid')->set('class', 'hidei');
		//->set('class', 'readonly');
		//$this->_view['form']->groupid=;
    }

	/*Host Manage*/
	function actionManage()
    {
		
		// 设置页面列表数目
		$pagesize = 4;
		// 获取当前页数，通常为get方式参数
		$page = $this->_context->page;
		$this->_view['pageno']=$page;
		$select = Hostgroup::find()->limitPage($page, $pagesize);
		$this->_view['pager'] = $select->getPagination();
		$this->_view['group'] = $select->order("id desc")->getAll();
		//echo $this->_view['pager']['record_count'];
		$pagediv = new Helper_MyPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'index.php?controller=hostmanage&action=manage&page=','',5);
		$this->_view['pagestr']= $pagediv->show();
    }

	/*Host Manage*/
	function actionAddform()
    {
		$this->_view['form'] = new Form_HostgroupAdd(url('default::hostmanage/groupadd'));
    }

	/*Host Manage*/
	function actionImportform()
    {
		$this->_view['form'] = new Form_HostuploadAdd(url('default::hostmanage/upload'));
    }

	/*Host Manage*/
	function actionHostAddform()
    {
		$this->_view['form'] = new Form_HostAdd(url('default::hostmanage/shost'));
    }

	/*Host Manage*/
	function actionHostImportform()
    {
		$this->_view['form'] = new Form_HostImport(url('default::hostmanage/importhost'));
    }

	/*Host Manage*/
	function actionList()
    {
		


		if ($this->_app->currentUserRoles())
        {
            
        //区分用户
		$os = array("admin");
		 //dump($_SESSION);
		 //echo $_SESSION['acl_task_userdata']['user_id'];
		 //$_SESSION['acl_task_userdata']['roles']
		 
		 $aroles = array();
		 $aroles =split('[,]', $_SESSION['acl_task_userdata']['roles']);
		 //dump($aroles);
		 $isrightp=false;
		 foreach ($aroles as $value){
			if (in_array(strtolower($value), $os)) {
				$isrightp=true;
				break;
				//echo "Got Irix";
			}
		 }
		 //echo $isrightp;
		 //echo $_SESSION['acl_task_userdata']['user_id'];
		$havegroups = array();
		$select1 = Groupuser::find('userid = ?',$_SESSION['acl_task_userdata']['user_id'])->getAll();
		foreach ($select1 as $av){
			array_push($havegroups,$av->groupid);
			//echo $av->groupid;
		}
		$addconds='';
		$this->_view['adming']=count($havegroups);
		if(count($havegroups)>0){

		if(!$isrightp && count($havegroups)>0)$addconds='id in ('.join(",",$havegroups).')';
		
		//dump($select1);
		$this->_view['form'] = new Form_SearchGroup(url('default::hostmanage/list'));
		if ($this->_context->searchtxt!='')
        {
			
			$pagesize = 1;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;
			$this->_view['stxt']=$this->_context->searchtxt;
			$select = Hostgroup::find('groupname like \'%'.$this->_context->searchtxt.'%\'')->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			if($this->_view['pager']['record_count']>0 && $page=='')
				$page=1;
			//echo $this->_view['pager']['record_count'];
			if($this->_context->searchtxt=='')
				$pagediv = new Helper_MyPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'index.php?controller=hostmanage&action=list&page=','',5);
			else
				$pagediv = new Helper_MyPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'index.php?controller=hostmanage&action=list&searchtxt='.$this->_context->searchtxt.'&page=','',5);
			$this->_view['pagestr']= $pagediv->show();


		}else{
		
		
		// 设置页面列表数目
		$pagesize = 4;
		// 获取当前页数，通常为get方式参数
		$page = $this->_context->page;
		$this->_view['pageno']=$page;
		$select = Hostgroup::find($addconds)->limitPage($page, $pagesize);
		$this->_view['pager'] = $select->getPagination();
		$this->_view['group'] = $select->order("id desc")->getAll();
		if($this->_view['pager']['record_count']>0 && $page=='')
			$page=1;
		//echo $this->_view['pager']['record_count'];
		$pagediv = new Helper_MyPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'index.php?controller=hostmanage&action=manage&page=','',5);
		$this->_view['pagestr']= $pagediv->show();
		//$xxx = new Helper_MyPager("grouprulexx.tpl");
		//$this->_view['form'] = new Form_HostgroupAdd(url('default::hostmanage/groupadd'));

		}

		}

		}
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }

	function actionView()
    {
        $show_box['title'] = '查看主机组';
        // 查询指定用户 ID
        $show_box['main_info'] = Hostgroup::find('id = ?', $this->_context->group_id )->query();
        if ( !$show_box['main_info'] -> id() )
        { // 如果 ID 无效，则返回用户管理首页
            return $this->_redirect(url('default::hostmanage/manage'));
        }
        $this->_view['show_box'] = $show_box;
		//echo 'qwq';
		//$this->_view['group'] = Hostgroup::find()->order('id desc')->getAll();
		//$this->_view['form'] = new Form_HostgroupAdd(url('default::hostmanage/groupadd'));
		//$show_box['title'] = '主机管理';
    }

	/* ******************************************************************** */
    function actionEdit()
    {
        $show_box['title'] = '编辑主机组';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');
		
			// 查询指定 ID
			$db_one = Hostgroup::find('id = ?', $this->_context->id )->query();
			if ( !$db_one->id() )
			{ // 如果 ID 无效，则返回
						//return $this->_redirect(url('admin::groups/index'));
			//                return $this->_redirectMessage(
			//                    '分组ID无效', 
			//                    '分组ID无效，请检查你的表单。',
			//                    url('default::hostmanage/manage'));
			}
			// 构造表单对象
			$show_box['form'] = $form = new Form_HostgroupAdd(url('default::hostmanage/edit'));
			$show_box['form']->_subject = $show_box['title'];
			if ($this->_context->isPOST() && $show_box['form'] -> validate($_POST))
			{
				try{
					// changeProps() 方法可以批量修改  对象的属性，但不会修改只读属性的值
					$db_one->changeProps($show_box['form']->values());
					$db_one->save();
					//return $this->_redirect(url('default::hostmanage/manage'));
				}
				catch (QValidator_ValidateFailedException $ex)
				{
					$show_box['form']->invalidate($ex);
				}
			}elseif (!$this->_context->isPOST()){
				// 如果不是 POST 提交，则把对象值导入表单
				$show_box['form']->import($db_one);
				$show_box['form']->add(QForm::ELEMENT, 'id', array('_ui' => 'hidden','value'=> $db_one->id()));
				//$show_box['form']->import(array('group_id'=>$db_one->id()));
			}
			//print_r($show_box);
			$this->_view['show_box'] = $show_box;
			$this->_viewname = 'form';

		}
    }

	function actionEdithost()
    {
        $show_box['title'] = '编辑主机';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');
		
			// 查询指定 ID
			$db_one = Hostgroup::find('id = ?', $this->_context->id )->query();
			if ( !$db_one->id() )
			{ // 如果 ID 无效，则返回
						//return $this->_redirect(url('admin::groups/index'));
			//                return $this->_redirectMessage(
			//                    '分组ID无效', 
			//                    '分组ID无效，请检查你的表单。',
			//                    url('default::hostmanage/manage'));
			}
			// 构造表单对象
			$show_box['form'] = $form = new Form_HostgroupAdd(url('default::hostmanage/edit'));
			$show_box['form']->_subject = $show_box['title'];
			if ($this->_context->isPOST() && $show_box['form'] -> validate($_POST))
			{
				try{
					// changeProps() 方法可以批量修改  对象的属性，但不会修改只读属性的值
					$db_one->changeProps($show_box['form']->values());
					$db_one->save();
					//return $this->_redirect(url('default::hostmanage/manage'));
				}
				catch (QValidator_ValidateFailedException $ex)
				{
					$show_box['form']->invalidate($ex);
				}
			}elseif (!$this->_context->isPOST()){
				// 如果不是 POST 提交，则把对象值导入表单
				$show_box['form']->import($db_one);
				$show_box['form']->add(QForm::ELEMENT, 'id', array('_ui' => 'hidden','value'=> $db_one->id()));
				//$show_box['form']->import(array('group_id'=>$db_one->id()));
			}
			//print_r($show_box);
			$this->_view['show_box'] = $show_box;
			$this->_viewname = 'form';

		}
    }

    /* ******************************************************************** */
    function actionDel()
    {
        $show_box['title'] = '删除主机组';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');
			//注意设定用户删除的锁定
			if($this->_context->id)
			{
				$group_id = $this->_context->id;
				Hostgroup::meta()->destroyWhere('id = ?', $group_id);
				if(mysql_affected_rows())
				{
					//清空组规则，标记groupid-1，未删除数据
					$table =QDB::getConn();
					$sql = "update `config` set `groupid`=-1 where `groupid`=".$group_id;
					$handel =$table->execute($sql);
					
					return $this->_redirectMessage(
					'主机组删除成功', 
					'指定主机组删除成功',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
				}
				else
				{
					return $this->_redirectMessage(
					'主机组删除失败', 
					'指定主机组删除失败',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
				}
			}
			else
			{
				return $this->_redirectMessage(
					'错误操作', 
					'操作错误，返回首页',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
			}
		}
    }

	function actionDeladmin()
    {
        $show_box['title'] = '删除主机组管理员';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');
			//注意设定用户删除的锁定
			if($this->_context->id)
			{
				$group_id = $this->_context->id;
				list($unum, $gnum,$gname) = explode('|', $group_id);
				GrouptoUser::meta()->destroyWhere('userid = ? and groupid = ?', $unum,$gnum);
				if(mysql_affected_rows())
				{
					return $this->_redirectMessage(
					'主机组管理员删除成功', 
					'指定主机组管理员删除成功',
					url('default::default/framework', array('id' => $gnum.'|'.$gname,'control' => 'hostmanage','acts' => 'views|search','groupid' => $gnum))
					);
				}
				else
				{
					return $this->_redirectMessage(
					'主机组管理员删除失败', 
					'指定主机组管理员删除失败',
					url('default::default/framework', array('id' => $gnum.'|','control' => 'hostmanage','acts' => 'views|search','groupid' => $gnum))
					);
				}
			}
			else
			{
				return $this->_redirectMessage(
					'错误操作', 
					'操作错误，返回首页',
					url('default::default/framework', array('id' => $gnum.'|','control' => 'hostmanage','acts' => 'views|search','groupid' => $gnum))
					);
			}
		}
    }


	function actionState()
    {
        $show_box['title'] = '主机状态';
		
		
		// 设置页面列表数目
		$pagesize = 10;
		// 获取当前页数，通常为get方式参数
		$page = $this->_context->page;
		$this->_view['pageno']=$page;
		$select = Host::find('[group.groupid]= ?',$this->_context->id)->limitPage($page, $pagesize);
		
		$this->_view['gid']=$this->_context->id;
		$this->_view['pager'] = $select->getPagination();
		$this->_view['manage'] = $select->order("id desc")->getAll();
		$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
		if($this->_view['pager']['record_count']>0 && $page=='')
			$page=1;

		$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'hostmanage|state|','\')',5);
		$this->_view['pagestr']= $pagediv->show();

		//$this->_view['manage'] = Host::find('[group.groupid]= ?',$this->_context->groupid)->order('id desc')->getAll();
		
    }

	/* ******************************************************************** */
    function actionDelhost()
    {
        $show_box['title'] = '删除主机';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');
			//注意设定用户删除的锁定
			if($this->_context->id)
			{
				$group_id = $this->_context->id;
				HostList::meta()->destroyWhere('id = ?', $group_id);
				GrouptoHost::meta()->destroyWhere('hostid = ?',$group_id);
				if(mysql_affected_rows())
				{
					return $this->_redirectMessage(
					'主机删除成功', 
					'指定主机删除成功',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
				}
				else
				{
					return $this->_redirectMessage(
					'主机组删除失败', 
					'指定主机删除失败',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
				}
			}
			else
			{
				return $this->_redirectMessage(
					'错误操作', 
					'操作错误，返回首页',
					url('default::default/framework', array('control' => 'hostmanage','acts' => 'admins|quick'))
					);
			}
		}
    }
    
 /* ******************************************************************** */
    function actionBind()
    {//删除权限-从中间表删除相关联系，用中间表模型
        $show_box['title'] = '用户组角色绑定';

        $group_id = $this->_context->group_id;
        //$roles = array('3'=>'1','4'=>'0','5'=>'1','2'=>'n','6'=>'n',);
        // 查询指定用户 ID
        $show_box['group_info'] = Hostgroup::find('group_id = ?', $group_id )->getOne();
        if ( !$show_box['group_info'] -> id() )
        { // 如果用户 ID 无效，则返回用户管理首页
            return $this->_redirect(url('admin::groups/index'));
        }
		
		//找出所有角色信息
        $show_box['roles'] =  Admin_Roles::find()->asArray()->getAll();
		//找出该用户所具有的角色信息
        $group_roles =  Admin_GroupsHaveRoles::find('group_id = ?',$group_id )->asArray()->getAll();
        //print_r($group_roles);
        
        foreach ($group_roles as $value){
            $show_box['group_roles'][$value['role_id']] = $value['is_include'];
        }
		//取得数组中的所有键值
        $show_box['group_roles']['role_id'] = array_keys( $show_box['group_roles'] );

        if ($this->_context->isPOST() )
        {
        	//$test_arr = $this->_context->role_id->toArray();
        	//echo count($test_arr);
            foreach ($this->_context->role_id as $key=>$value){
				//"n"表示用户对应的角色（或权限）为NULL，是空的
                if ($value == 'n'){
                    Admin_GroupsHaveRoles::meta()->destroyWhere('group_id = ? AND role_id = ?', $group_id, $key);
                }else{
                    $find_one = Admin_GroupsHaveRoles::find('group_id = ? AND role_id = ?', $group_id, $key)->query();
                    if ($find_one['group_id']){
                        Admin_GroupsHaveRoles::meta()->updateDbWhere( array('is_include'=>$value), 'group_id = ? AND role_id = ?', $group_id, $key);
                        // 不能用以下这个方法，会添加重复记录，因为没有主键
                        //$find_one->is_include = $value;
                        //$find_one->save();
                    }else{
                    	//echo $group_id.'--'.$value.'--'.$key.'<br/>';
                        $add_one = new Admin_GroupsHaveRoles(array('group_id'=>$group_id,'role_id'=>$key,'is_include'=>$value));
                        $add_one->save();
                    }
                }
            }
            return $this->_redirectMessage(
                '用户组权限设定成功', 
                '指定用户组权限设定成功',
                url('admin::groups/bind',array('group_id'=>$group_id))
                );
        }
        
        $this->_view['show_box'] = $show_box;
    }

	function actionGroupadd()
    {
        $show_box['title'] = '添加主机组';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');

		
			$form = new Form_HostgroupAdd(url('default::hostmanage/groupadd'));
			
			// 查询指定用户 ID
			$sid = Hostgroup::find('groupname = ?', $_POST['groupname'])->getOne();
			//dump($sid -> id());
			if ( !$sid -> id() )
			{ // 如果用户 ID 无效，则返回用户管理首页
				//return $this->_redirect(url('admin::groups/index'));
				try{
					if($form->validate($_POST)){
						$newgroup= new Hostgroup($form->values());
						$newgroup->save();
						//return true;
						//return '<div id="postContent">添加成功<div>';
					}
				}catch(QValidation_FailedException $ex){
					$form->invalidate($ex);
					//return false;
				}

				$this->_view['form']=$form;
				
			}else{

				//dump('asdasd');
				
				//return '同名主机组已存在';
				return '1';
			}
			

			
		}
    }

	function actionHostadd()
    {
        $form = new Form_HostAdd(url('default::hostmanage/hostadd'));
		
		try{
			if($form->validate($_POST)){
				$newgroup= new Hostgroup($form->values());
				$newgroup->save();

				//return '<div id="postContent">添加成功<div>';
			}
		}catch(QValidation_FailedException $ex){
			$form->invalidate($ex);
		}

		$this->_view['form']=$form;
		//$show_box['title'] = '测试操作1111111111111111';
        //dump($_SESSION);
    }

    /**1**/
	function actionShost()
    {
        $show_box['title'] = '添加新主机';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');
		
			$form = new Form_HostAdd(url('default::hostmanage/shost'));
			
			try{
				if($form->validate($_POST)){
					$newgroup= new Host($form->values());
					$newgroup->save();

					//return '<div id="postContent">添加成功<div>';
				}
			}catch(QValidation_FailedException $ex){
				$form->invalidate($ex);
			}

			$this->_view['form']=$form;

		}
    }

	function actionGroupone()
    {
        $form = new Form_HostgroupAdd(url('default::hostmanage/groupadd'));
		
		try{
			if($form->validate($_POST)){
				$newgroup= new Hostgroup($form->values());
				$newgroup->save();

				return $this->_redirect(url('default::hostmanage/manage'));
			}
		}catch(QValidation_FailedException $ex){
			$form->invalidate($ex);
		}

		$this->_view['form']=$form;
		//$show_box['title'] = '测试操作';
        //dump($_SESSION);
    }

	function actionBlanks(){
		$demo = array();
		// 设置页面列表数目
		$pagesize = 10;
		// 获取当前页数，通常为get方式参数
		//$_REQUEST['start']
		$page = ($_REQUEST['start']/$_REQUEST['limit'])+1;
		$this->_view['pageno']=$page;
		$select = Host::find('grouptohost.groupid is null')->joinLeft('grouptohost', 'groupid', 'grouptohost.hostid = hosttable.id')->limitPage($page,$_REQUEST['limit']);
		$allc=$select->getPagination();
		$totaldata = $allc['record_count'];
		$demostr=$select->order("id desc")->getAll()->toArray();
		$date = date("Y-m-d");
		for($i=0; $i<count($demostr); $i++){
			$demo[] = array("date"=>$demostr[$i]['id'],"pageview"=>$demostr[$i]['hostname'],"ip"=>$demostr[$i]['macaddress'],"visits"=>$demostr[$i]['ostype'],"uv"=>$demostr[$i]['ipaddr'],"pvuv"=>$demostr[$i]['datetime'],"op"=>$demostr[$i]['descript']);
			$date = date("Y-m-d",strtotime($date)-24*3600);
			
		}
		

		//$demo_out = array_slice($demo,$_REQUEST['start'],$_REQUEST['limit']);
		$str = '({"total":"'.$totaldata.'","root":'.json_encode($demo).'})';
		//dump($demostr);
		echo $str;
	}

	/**1**/
	function actionBlank(){
		$show_box['title'] = '未分组主机';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');

			$this->_view['manage'] = Host::find('grouptohost.groupid is null')->joinLeft('grouptohost', 'groupid', 'grouptohost.hostid = hosttable.id')->getAll();
			$this->_view['form'] = new Form_BlankToGroup(url('default::hostlist/blind'));
		}
	}

	/*Host Manage*/
	function actionGroup()
    {
        //$this->_view['group'] = Host::find()->order('id desc')->getAll();
		//$show_box['title'] = '测试操作222222222222222222222222';
        //dump($_SESSION);
		//echo 'qwe';

		$this->_view['manage'] = Host::find()->order('id desc')->getAll();
		//$show_box['title'] = '测试操作222222222222222222222222';
        //dump($_SESSION);
		//echo 'qwe';

    }


	/**********/
	function actionTest(){
		//echo 'qwwqwq';
		$nca = Admin_Permissions::find()->getAll();

		foreach ( $nca as $value){
			 $roles_arr = $value->roles->toArray();
			 echo $value['permission_id'].'<br>';
			 print_r($roles_arr);
			 echo '<br>----------------------<br>';
		}
	}

    /* ******************************************************************** */
    function actionIndex()
    {
        $show_box['title'] = '默认首页';
        if ($this->_app->currentUserRoles())
        {
            // 如果已经登录，就转到任务列表页面
            $show_box['ncArrs'] = Helper_Permissions::getNamespaceControllerArrs();
            $this->_view['show_box'] = $show_box;
        }
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }

}